package org.goobs.chess;

import org.goobs.chess.ChessPosition.PositionInformation;
import org.goobs.io.Console;
import org.goobs.io.GuiConsole;

public class ChessGame {
	
	protected static Console console = GuiConsole.get();
	
	private ChessPosition currentGame;
	private ChessAgent whiteAgent;
	private ChessAgent blackAgent;
	private int turn;
	private int victor = -1;
	
	public ChessGame(){
		this.currentGame = new ChessPosition();
		this.turn = ChessAgent.WHITE;
	}
	
	public void sitDown(ChessAgent agent){
		if(agent.getColor() == ChessAgent.WHITE){
			whiteAgent = agent;
		}else if(agent.getColor() == ChessAgent.BLACK){
			blackAgent = agent;
		}else{
			throw new IllegalArgumentException("Not a valid color: " + agent.getColor());
		}
	}
	
	public ChessPosition play(){
		while( !whiteAgent.claimsVictory() && !blackAgent.claimsVictory() ){
			//--Player moves
			if(turn == ChessAgent.WHITE){
				currentGame.printToConsole(console);
				ChessMove move = whiteAgent.decideMove(currentGame);
				currentGame = currentGame.move(move);
			}else{
				currentGame.printToConsole();
				ChessMove move = blackAgent.decideMove(currentGame);
				currentGame = currentGame.move(move);
			}
			turn = (turn+1) % 2;
			//--Check for victory
			PositionInformation info = currentGame.calculateInformation(turn);
			if(info.getChildren().size() == 0){
				//(check mate)
				victor = (turn+1)%2;
				break;
			}
		}
		if(whiteAgent.claimsVictory()){
			victor = ChessAgent.WHITE;
		}
		if(blackAgent.claimsVictory()){
			victor = ChessAgent.BLACK;
		}
		return currentGame;
	}
	
	public int getVictor(){
		return victor;
	}
	
	private static final String toColor(int color){
		if(color == ChessAgent.WHITE){
			return "WHITE";
		}else{
			return "BLACK";
		}
	}
	
	
	
	public static void main(String[] args){
		ChessAgent white = new HumanChessAgent(ChessAgent.WHITE);
		ChessAgent black = new ComputerChessAgent(ChessAgent.BLACK);
		ChessGame game = new ChessGame();
		game.sitDown(white);
		game.sitDown(black);
		game.play();
		System.out.println();
		System.out.println();
		System.out.println();
		System.out.println("VICTOR: " + toColor(game.getVictor()));
	}
}
